﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Linq;
using Pipra.Gis.Ogc;
using Pipra.Math.Geometry;
using Pipra.Uom;

namespace Pipra.Gis
{    
    public class AuthorityFactoryManager
    {

        public class PluginContainer : IEnumerable<IAuthorityFactory>
        {
            internal PluginContainer()
            {
                IEnumerable<ComposablePartCatalog> catalogs = new ComposablePartCatalog[]
                {
                    new AssemblyCatalog(typeof (IAuthorityFactory).Assembly),
                    new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory),
                };
                string binPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin");
                if(Directory.Exists(binPath))
                {
                    catalogs.Concat(new ComposablePartCatalog[] {new DirectoryCatalog("bin") });
                }
                _catalog = new AggregateCatalog(catalogs);
                _container = new CompositionContainer(_catalog);
                _container.ComposeParts(this);
            }

            private readonly ComposablePartCatalog _catalog;
            private readonly CompositionContainer _container;

            [ImportMany(AllowRecomposition = true)]
            public IEnumerable<IAuthorityFactory> Factories { get; set; }

            public IEnumerator<IAuthorityFactory> GetEnumerator()
            {
                return (Factories ?? Enumerable.Empty<IAuthorityFactory>()).GetEnumerator();
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
            {
                return GetEnumerator();
            }
        }

        private static AuthorityFactoryManager _default;

        /// <summary>
        /// The default authority factory manager.
        /// </summary>
        public static AuthorityFactoryManager Default
        {
            get { return _default ?? (_default = new AuthorityFactoryManager(new PluginContainer())); }
        }

        private readonly IEnumerable<IAuthorityFactory> _container;

        public AuthorityFactoryManager(IEnumerable<IAuthorityFactory> factories)
        {
            _container = factories ?? new IAuthorityFactory[0];
        }

        public IEnumerable<string> GetSupportedAuthorities()
        {
            return Factories.Select(af => af.AuthorityName).Distinct();
        }

        public bool NameMatches(string name)
        {
            return Factories.Any(af => af.NameMatches(name));
        }

        public IEnumerable<IAuthorityFactory> Factories { get { return _container.AsEnumerable(); } }

        private IEnumerable<IAuthorityFactory> ValidAuthsForTag(IAuthorityTag tag) {
            return null == tag
                ? Enumerable.Empty<IAuthorityFactory>()
                : ValidAuthsForName(tag.Name)
            ;
        }

        private IEnumerable<IAuthorityFactory> ValidAuthsForName(string authName) {
            return Factories.Where(f => f.NameMatches(authName));
        }

        public IAuthorityTag CreateAuthorityTag(string authName, string code)
        {
            return ValidAuthsForName(authName)
                .Select(fac => fac.CreateAuthorityTag(code))
                .FirstOrDefault(o => null != o)
            ;
        }

        public ISpheroid<double> CreateSpheroid(IAuthorityTag tag) {
            
            return ValidAuthsForTag(tag)
                .Select(f => f.CreateSpheroid(tag.Code))
                .FirstOrDefault(o => null != o)
            ;
        }

        public IPrimeMeridian CreatePrimeMeridian(IAuthorityTag tag) {
            return ValidAuthsForTag(tag)
                .Select(f => f.CreatePrimeMeridian(tag.Code))
                .FirstOrDefault(o => null != o)
            ;
        }

        public IUom CreateUom(IAuthorityTag tag) {
            return ValidAuthsForTag(tag)
                .Select(f => f.CreateUom(tag.Code))
                .FirstOrDefault(o => null != o)
            ;
        }

    }
}
